建立angular library
1.建立空專案
ng new app-test-lib --create-application=false --routing false --style css
2.於 projects 下建立libraryng g library app-lib
@Component({
selector: 'lib-app-lib',
template: `
<p>
app-lib works! OK
</p>
`,
styles: []
})
export class AppLibComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
3.於 projects 下建立測試 library 的專案ng g application app-test
app-test-web
----node_modules
----projects
--------app-lib
--------app-test
4.於app-test-web 先 ng build 產生distC:\app-test-lib> ng build
5.設定path
(1)於app-test-web 下的 tsconfig.json
增加 "projects/app-lib/src/public-api.ts"
"paths": {
"app-lib": [
"dist/app-lib",
"projects/app-lib/src/public-api.ts"
]
}
(2)src/public-api.ts
是設定 library 要 export 的項目
export * from './lib/app-lib.service';
export * from './lib/app-lib.component';
export * from './lib/app-lib.module';
6.於 app-test 使用 app-lib
於 app.module.ts import AppLibModule,
藉由 "projects/app-lib/src/public-api.ts"
導向到build完的app-lib
import { AppLibModule } from 'app-lib';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
AppLibModule
],
7.於app-test測試app-lib專案
(1)將app-test ng serveC:\app-test-lib> ng serve app-test
(2) build app-lib library專案 並 -- watchC:\app-test-lib> ng build app-lib --watch
這樣 app-lib 只要有更改,可以直接在 app-test 看到結果
**8.於 app.component.html 加上 **<lib-app-lib></lib-app-lib>
確認結果。
參考連結:
Angular.io :
https://angular.io/guide/creating-libraries
保哥:
https://blog.miniasp.com/post/2019/04/19/Learn-Angular-Library-and-build-custom-Form-Validators